package com.hnichr.ump.common.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.hnichr.ump.common.ping.vo.SendResultVo;
import com.hnichr.ump.common.service.SmsService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

@Service
public class SmsServiceImpl implements SmsService {

    @Value("${sms.url}")
    private String smsUrl;

    public String sendSms(String smsContent,String mobile,String appKey,String appSecret) {
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("appKey",appKey);
        treeMap.put("mobiles",mobile);
        treeMap.put("smsContent",smsContent);
        treeMap.put("timestamp",String.valueOf(System.currentTimeMillis()));
        treeMap.put("nonce", UUID.fastUUID().toString(true));
        treeMap.put("signatureMethod","HMAC-SHA1");
        String signature = getSignature(treeMap,appSecret);
        treeMap.put("signature",signature);

        HttpResponse response = HttpUtil.createPost(smsUrl).contentType("application/json").body(JSON.toJSONString(treeMap)).execute();
        SendResultVo resultVo = JSON.parseObject(response.body(),SendResultVo.class);
        return resultVo.getCode();
    }


    private String getSignature(TreeMap<String,String> treeMap,String appSecret){
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(appSecret.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            org.apache.commons.codec.binary.Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }
}
